package cc.jq1024.domain.rebate.service;

import cc.jq1024.domain.rebate.event.SendRebateMessageEvent;
import cc.jq1024.domain.rebate.model.aggregate.BehaviorRebateAggregate;
import cc.jq1024.domain.rebate.model.entity.BehaviorEntity;
import cc.jq1024.domain.rebate.model.entity.BehaviorRebateOrderEntity;
import cc.jq1024.domain.rebate.model.entity.BehaviorRebateTaskEntity;
import cc.jq1024.domain.rebate.model.valobj.BehaviorRebateTaskStateVO;
import cc.jq1024.domain.rebate.model.valobj.DailyBehaviorRebateVO;
import cc.jq1024.domain.rebate.repository.IBehaviorRebateRepository;
import cc.jq1024.types.common.Constants;
import cc.jq1024.types.event.BaseEvent;
import cc.jq1024.types.snow.SnowflakeIdGenerator;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author: jia-qiang ljq1024.cc
 * @desc: 用户行为返利服务接口实现
 * @Date: 2024-06-29-23:55
 */
@Service
@AllArgsConstructor
public class BehaviorRebateService implements IBehaviorRebateService {

    private final SnowflakeIdGenerator snowflakeIdGenerator;
    private final SendRebateMessageEvent sendRebateMessageEvent;
    private final IBehaviorRebateRepository behaviorRebateRepository;

    /**
     * 返利订单 - 签到？支付？
     *
     * @param behaviorEntity 行为实体
     * @return 单号 - 可能会是数组
     */
    @Override
    public List<String> createOrder(BehaviorEntity behaviorEntity) {
        // 1. 查询返利配置
        List<DailyBehaviorRebateVO> dailyBehaviorRebateVOS =
                behaviorRebateRepository.queryDailyBehaviorRebateConfig(behaviorEntity.getBehaviorTypeVO());
        if (null == dailyBehaviorRebateVOS || dailyBehaviorRebateVOS.isEmpty()) return Collections.emptyList();

        // 2. 构建聚合对象
        List<String> orderIds = new ArrayList<>(dailyBehaviorRebateVOS.size());
        List<BehaviorRebateAggregate> behaviorRebateAggregates = new ArrayList<>(dailyBehaviorRebateVOS.size());
        for (DailyBehaviorRebateVO dailyBehaviorRebateVO : dailyBehaviorRebateVOS) {
            // 2.1 拼接业务ID；用户ID_返利类型_外部透彻业务ID
            String bizId = behaviorEntity.getUserId() + Constants.UNDERLINE + dailyBehaviorRebateVO.getRebateType() + Constants.UNDERLINE + behaviorEntity.getOutBusinessNo();
            // 2.2 构建订单对象
            BehaviorRebateOrderEntity behaviorRebateOrderEntity = BehaviorRebateOrderEntity.builder()
                    .userId(behaviorEntity.getUserId())
                    .orderId(snowflakeIdGenerator.nextId())
                    .behaviorType(dailyBehaviorRebateVO.getBehaviorType())
                    .rebateDesc(dailyBehaviorRebateVO.getRebateDesc())
                    .rebateType(dailyBehaviorRebateVO.getRebateType())
                    .rebateConfig(dailyBehaviorRebateVO.getRebateConfig())
                    .outBusinessNo(behaviorEntity.getOutBusinessNo())
                    .bizId(bizId)
                    .build();
            // 2.4 保存订单单号
            orderIds.add(String.valueOf(behaviorRebateOrderEntity.getOrderId()));

            // 2.5 构建 MQ 消息对象
            SendRebateMessageEvent.RebateMessage rebateMessage = SendRebateMessageEvent.RebateMessage.builder()
                    .userId(behaviorEntity.getUserId())
                    .rebateType(dailyBehaviorRebateVO.getRebateType())
                    .rebateConfig(dailyBehaviorRebateVO.getRebateConfig())
                    .bizId(bizId)
                    .build();

            // 2.6 构建事件消息
            BaseEvent.EventMessage<SendRebateMessageEvent.RebateMessage> rebateMessageEventMessage = sendRebateMessageEvent.buildEventMessage(rebateMessage);

            // 2.7 组装任务对象
            BehaviorRebateTaskEntity taskEntity = new BehaviorRebateTaskEntity();
            taskEntity.setUserId(behaviorEntity.getUserId());
            taskEntity.setTopic(sendRebateMessageEvent.topic());
            taskEntity.setMessageId(rebateMessageEventMessage.getId());
            taskEntity.setMessage(rebateMessageEventMessage);
            taskEntity.setState(BehaviorRebateTaskStateVO.create);

            // 2.8 构建聚合对象
            BehaviorRebateAggregate behaviorRebateAggregate = BehaviorRebateAggregate.builder()
                    .userId(behaviorEntity.getUserId())
                    .behaviorRebateOrderEntity(behaviorRebateOrderEntity)
                    .taskEntity(taskEntity)
                    .build();
            behaviorRebateAggregates.add(behaviorRebateAggregate);

        }

        // 3. 存储聚合对象数据
        behaviorRebateRepository.saveUserRebateRecord(behaviorEntity.getUserId(), behaviorRebateAggregates);

        // 4. 返回订单ID集合
        return orderIds;
    }

    /**
     * 根据外部单号查询订单
     *
     * @param userId        用户ID
     * @param outBusinessNo 业务ID；签到则是日期字符串，支付则是外部的业务ID
     * @return 返利订单实体
     */
    @Override
    public List<BehaviorRebateOrderEntity> queryOrderByOutBusinessNo(String userId, String outBusinessNo) {
        return behaviorRebateRepository.queryOrderByOutBusinessNo(userId, outBusinessNo);
    }

}
